package com.vip8.recorder.service.utils;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 日期工具类
 */
public class DateUtil {

    /**
     * 格式： 2021-01-11
     */
    public final static String FORMAT_YMD = "yyyy-MM-dd";

    /**
     * 格式： 2021-01-11
     */
    public final static String FORMAT_TIMESTAMP = "yyyy-MM-dd HH:mm:ss";



    public static Date parse(String date) {
        if (StringUtil.isEmpty(date)) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIMESTAMP);
        try {
            return format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字符串类型转换为固定格式的日志
     *
     * @param date    日期字符串
     * @param pattern 日期格式
     * @return
     * @throws ParseException
     */
    public static Date parse(String date, String pattern) {
        if (StringUtil.isEmpty(date)) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            return format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将日期格式转换为字符串
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        return format(date, pattern, null, null);
    }

    /**
     * @param date
     * @param pattern
     * @param timeZone
     * @param locale
     * @return
     */
    public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {
        if (date == null) {
            return null;
        }
        FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
        return df.format(date);
    }

    public static String addYear(Date date, int amount, String pattern) {
        Date newDate = DateUtils.addYears(date, amount);
        return format(newDate, pattern);
    }

    public static String addMonth(Date date, int amount, String pattern) {
        Date newDate = DateUtils.addMonths(date, amount);
        return format(newDate, pattern);
    }

    public static Date addMonth(Date date, int amount) {
        return DateUtils.addMonths(date, amount);
    }

    public static Date addHours(Date date, int amount) {
        return DateUtils.addHours(date, amount);
    }

    public static String addMin(Date date, int amount, String pattern) {
        Date newDate = DateUtils.addMinutes(date, amount);
        return format(newDate, pattern);
    }
}
